package com.rpframework.core.config.zookeeper;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

/**
 * spring加载配置文件从zookeeper更新重写
 * 
 * @author 刘兴
 */
public class ZooKeeperPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

	public final Logger log = LoggerFactory.getLogger(getClass());

	/**
	 * 配置地址地址
	 */
	public String path;
	/**
	 * 配置
	 */
	private Config config;

	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
			throws BeansException {
		super.processProperties(beanFactoryToProcess, props);

		try {
			fillCustomProperties(props);
		} catch (Exception e) {
			log.error("zokeeper加载配置文件失败", e);
		}
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public Config getConfig() {
		return config;
	}

	public void setConfig(Config config) {
		this.config = config;
	}

	private void fillCustomProperties(Properties props) throws Exception {
		byte[] data = getData(props);
		fillProperties(props, data);
	}

	private void fillProperties(Properties props, byte[] data) throws UnsupportedEncodingException {
		String cfg = new String(data, "UTF-8");
		if (StringUtils.isNotBlank(cfg)) {
			// 完整的应该还需要处理：多条配置、value中包含=、忽略#号开头
			String[] cfgItem = StringUtils.split(cfg, "=");
			props.put(cfgItem[0], cfgItem[1]);
		}
	}

	/**
	 * 获取数据
	 * 
	 * @param props
	 *            配置对象
	 * @return 流
	 * @throws Exception
	 *             获取失败
	 */
	private byte[] getData(Properties props) throws Exception {
		String chlidPath = props.getProperty(path);
		return config.getConfig(chlidPath);
	}

}